//
//  DateRange.swift
//  CoreDataForPOCT
//
//  Created by Ryan Chen on 21/03/2018.
//  Copyright © 2018 Ryan Chen. All rights reserved.
//

import Foundation

public class DateRange {
    private var begin = Date()
    private var end = Date()
    private var calendar: Calendar!
    
    static let secs : TimeInterval = 86399 // 24*60*60 - 1
    
    public init(begin: Date?, end: Date?, calendar: Calendar?) {
        if let b = begin {
            self.begin = b
        }
        
        if let e = end {
            self.end = e
        }
        
        if (self.begin > self.end) {
            Swift.print("=> Error in DateRange, begin > end")
        }
        
        if let c = calendar {
            self.calendar = c
        } else {
            self.calendar = Calendar.current
        }
    }
    
    func dump() -> Void {
        let df = DateFormatter()
        df.dateFormat = "yyyy-MM-dd"
        Swift.print("duration: \(self.count) begin: \(df.string(from:self.begin)) end: \(df.string(from:self.end))")
    }
    
    var count : Int {
        get {
            return days(begin: self.begin, end: self.end)
        }
    }
    
    // begin - end
    public func days(begin: Date, end: Date) -> Int {
        let b = calendar.startOfDay(for: begin)
        let e = calendar.startOfDay(for: end) + DateRange.secs
        let c = calendar.dateComponents([.day], from:b, to:e)
        return c.day! + 1
    }
    
    public enum Relation {
        case before
        case inside
        case after
    }
    
    public func relation(to today: Date) -> (Relation, Int) {
        let date = calendar.startOfDay(for: today)
        
        if begin...end ~= date {
            return (.inside, 0)
        } else {
            if date < self.begin {
                return (.before, days(begin: date, end: self.begin))
            } else {
                return (.after, days(begin: self.end, end: date))
            }
        }
    }
}
